package com.example.game2048;

import java.util.LinkedList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.util.NumList;

public class MainActivity extends Activity {

	// 分别为目前最大的数字， 目前得分，历史最高得分的TextView
	private TextView tvLargestNum, tvScore, tvBestScore;
	
	// most_score现在最大的数字,all_score为目前的得分
	private int largestNum = 0, score = 0;
	private static MainActivity mainactivity;
	private SharedPreferences mySharedPreferences;
	private SharedPreferences.Editor editor;
	MyGridView myGridView;
	
	
	//判断是否已经赢了
	private boolean hasWon = false;

	public boolean isHasWon() {
		return hasWon;
	}

	public void setHasWon(boolean hasWon) {
		this.hasWon = hasWon;
	}

	public MainActivity() {
		super();
		mainactivity = this;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tvLargestNum = (TextView) findViewById(R.id.now_most_score);
		tvScore = (TextView) findViewById(R.id.now_all_score);
		tvBestScore = (TextView) findViewById(R.id.history_most_score);
		myGridView = (MyGridView) findViewById(R.id.mygirdview);

		mySharedPreferences = getSharedPreferences("my2048",
				Activity.MODE_PRIVATE);
		editor = mySharedPreferences.edit();
		tvBestScore.setText(mySharedPreferences.getInt("bestScore", 0) + "");
	}
	
	

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		NumList lastNumList = savedInstanceState.getParcelable("currentState");
		if(lastNumList != null) {
			int[] cardNums = new int[16];
			for(int i = 0; i < 16; i++) {
				cardNums[i] = lastNumList.getNumOfIndex(i);
			}
			myGridView.setMyCards(cardNums);
			score = lastNumList.getNumOfIndex(16);
			Log.d("score", score+"");
			myGridView.updateScore(0);
		}
		
		
	}
	
	

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		NumList numList = myGridView.getNumList();
		outState.putSerializable("currentState", numList);
	}

	public static MainActivity getMainActivity() {
		return mainactivity;
	}
	
	public void setUndoTimes(int n) {
		String undoTimes = getString(R.string.undo);
		undoTimes = String.format(undoTimes, n);
		Button btnUndo = (Button) findViewById(R.id.bth_undo);
		btnUndo.setText(undoTimes);
	}

	public void onReplay(View view) {
		myGridView.startGame();
		clearScore();
	}

	public void onUndo(View view) {
		String text = ((Button)findViewById(R.id.bth_undo)).getText().toString();
		int num = Integer.parseInt(text.replaceAll("\\D", ""));
		if(num >0 ) {
			boolean res = retrieveGame();
			Log.d("retrieve", res+"");
			if(res) {
				num--;
				setUndoTimes(num);
			}
		}
		
	}

	public void clearScore() {
		score = 0;
		showScore();
		setHasWon(false);
	}

	// 刷新页面的分数 包括目前最大数字 得分 历史最高得分
	private void showScore() {
		tvLargestNum.setText(largestNum + "");
		Log.d("in showScore : score", score+"");
		tvScore.setText(score + "");
		tvBestScore.setText(mySharedPreferences.getInt("bestScore", 0) + "");
		if(score > Integer.parseInt(tvBestScore.getText().toString())) {
			tvBestScore.setText(score + "");
			editor.putInt("bestScore", score);
			// 提交当前数据
			editor.commit();
		}
		//当最大的数字为2048且 之前没有达到这个数字时
		if(largestNum == 128 && isHasWon() == false) {
			Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("You Win!");
			builder.setMessage("You won the game! You are a 2048 wizard!");
			builder.setPositiveButton("Continue", new OnClickListener(){

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					setHasWon(true);
				}
				
			});
			builder.setNegativeButton("Try Again", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					myGridView.startGame();
					clearScore();
				}
			});
			builder.show();
		}
	}

	/*
	 * 刷新页面的分数，其中laregest为目前最大的分数，increment为新增得分
	 */
	public void refreshScore(int largest, int increment) {
		largestNum = largest;
		Log.d("in refreshScore : score", score + "");
		score += increment;
		showScore();
	}
	
	public int getScore() {
		return score;
	}

	public void saveGame(NumList currentNumList) {
		String history = mySharedPreferences.getString("history", "");
		Log.d("history before", history);
		LinkedList<NumList> array = new LinkedList<NumList>();
		if(history != "") {
			for(String str : history.split("##")) {
				NumList numList = new NumList(str);
				array.add(numList);
			}
		}
		
//		NumList currentNumList = new NumList(17);
//		int i = 0;
//		for(MyCard[] myCards : myGridView.getMyCards()) {
//			for(MyCard myCard : myCards) {
//				currentNumList.setNumOfIndex(i++, myCard.getNum());
//			}
//		}
//		currentNumList.setNumOfIndex(16, score);
		array.add(currentNumList);
		Log.d("array's length", array.size() + "");
		while(array.size() >= 4) {
			array.removeFirst();
		}
		StringBuilder sb = new StringBuilder();
		int count = 1;
		for(NumList numList : array) {
			sb.append(numList.toString());
			if(count++ < array.size()) {
				sb.append("##");
			}
		}
		editor.putString("history", sb.toString());
		editor.commit();
		Log.d("history after", sb.toString());

	}

	public boolean retrieveGame() {
		String history = mySharedPreferences.getString("history", "");
		Log.d("history before  ret", history);

		LinkedList<NumList> array = new LinkedList<NumList>();
		if(history != "") {
			for(String str : history.split("##")) {
				NumList numList = new NumList(str);
				array.add(numList);
			}
		}
		if(array.size() == 0) {
			return false;
		}
		NumList lastNumList = array.pollLast();
		int[] cardNums = new int[16];
		for(int i = 0; i < 16; i++) {
			cardNums[i] = lastNumList.getNumOfIndex(i);
		}
		myGridView.setMyCards(cardNums);
		score = lastNumList.getNumOfIndex(16);
		Log.d("score", score+"");
		myGridView.updateScore(0);
		StringBuilder sb = new StringBuilder();
		int count = 1;
		for(NumList numList : array) {
			sb.append(numList.toString());
			if(count++ < array.size()) {
				sb.append("##");
			}
		}
		editor.putString("history", sb.toString());
		editor.commit();
		Log.d("history after ret", sb.toString());
		return true;
	}
	
	public void clearRecords() {
		editor.putString("history", "");
		editor.commit();
	}

}
